module.exports = function (options, app) {
    return async function text(ctx, next) {
        try {
            //获取用户信息
            var user = '';
            const userToken = ctx.get('Authorization') || '';

            if(userToken != ''){
                user = ctx.app.jwt.verify(userToken.substring(7), "123456");
            }

            //验证token是否合法
            const token = await ctx.service.cache.redis.get(user.id) || '';

            if (token == userToken) {
                //Redis可以找到信息。是登录状态。
                //验证账号状态
                const userInfo = await ctx.model.User.findOne({
                    where: {
                        id: user.id
                    }
                });

                if (userInfo.state == 1) {
                    //重置token有效期限
                    await ctx.service.cache.redis.set(user.id, token, 60 * 60 * 24 * 7, 0);
                    ctx.userInfo = userInfo
                    await next();
                }else{
                    ctx.response.body = {
                        code: 402,
                        data: {
                            state:userInfo.state
                        },
                        msg: 'The user status is incorrect'
                    }
                }

            } else {
                //登录失效
                ctx.response.body = {
                    code: 401,
                    data: {},
                    msg: 'Logon failure !'
                }
                return;
            }
        } catch (error) {
            ctx.response.body = {
                code: 400,
                data: {},
                msg: 'Error !'
            }
        }

    }
}